//添加树
var setting = {
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "areaCode",
					pIdKey: "areaParentCode"
				},
				key:{
					name:"areaName"
				}
			},
			callback: {
				beforeClick: beforeClick,
				onClick: onClick
			}
		};

		

		function beforeClick(treeId, treeNode) {
			var check = (treeNode && !treeNode.isParent);
			if (!check) 
				new $.zui.Messager('只能选择地区!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			return check;
		}
		
		function onClick(e, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("addtreeDemo"),
			nodes = zTree.getSelectedNodes(),
			v = ""; A = "";
			nodes.sort(function compare(a,b){return a.id-b.id;});
			for (var i=0, l=nodes.length; i<l; i++) {
				v += nodes[i].areaName + ",";
				A += nodes[i].areaCode ;
			}
			if (v.length > 0 ) v = v.substring(0, v.length-1);
			var cityObj = $("#citySel");
			cityObj.attr("value", v);
			var areaObj = $("#addArea_Code");
			areaObj.attr("value",A);
			console.log("地区编码="+A);
		}

		function showMenu() {
			var cityObj = $("#citySel");
			var cityOffset = $("#citySel").offset();
			$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

			$("body").bind("mousedown", onBodyDown);
		}
		function hideMenu() {
			$("#menuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown);
		}
		function onBodyDown(event) {
			if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
				hideMenu();
			}
		}
		$("#citySel").click(function(){
			 showMenu(); 
		});
//修改树		
		var settingUpdate = {
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true,
						idKey: "areaCode",
						pIdKey: "areaParentCode"
					},
					key:{
						name:"areaName"
					}
				},
				callback: {
					beforeClick: beforeClickUpdate,
					onClick: onClickUpdate
				}
			};

			

			function beforeClickUpdate(treeId, treeNode) {
				var check = (treeNode && !treeNode.isParent);
				if (!check) 
					new $.zui.Messager('只能选择地区!', {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				return check;
			}
			
			function onClickUpdate(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("updatetreeDemo"),
				nodes = zTree.getSelectedNodes(),
				v = ""; A = "";
				nodes.sort(function compare(a,b){return a.id-b.id;});
				for (var i=0, l=nodes.length; i<l; i++) {
					v += nodes[i].areaName + ",";
					A += nodes[i].areaCode ;
				}
				if (v.length > 0 ) v = v.substring(0, v.length-1);
				var cityObj = $("#updatecitySel");
				cityObj.prop("value", v);
				var areaObj = $("#updateArea_Code");
				areaObj.prop("value",A);
				console.log("地区编码="+A);
			}

			function showMenuUpdate() {
				var cityObj = $("#updatecitySel");
				var cityOffset = $("#updatecitySel").offset();
				$("#updatemenuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

				$("body").bind("mousedown", onBodyDownUpdate);
			}
			function hideMenuUpdate() {
				$("#updatemenuContent").fadeOut("fast");
				$("body").unbind("mousedown", onBodyDownUpdate);
			}
			function onBodyDownUpdate(event) {
				if (!(event.target.id == "menuBtn" || event.target.id == "updatemenuContent" || $(event.target).parents("#updatemenuContent").length>0)) {
					hideMenuUpdate();
				}
			}
			$("#updatecitySel").click(function(){
				 showMenuUpdate(); 
			});		
$(document).ready(function(){
	var merDevInfoService = "/api/merDev";
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	var tempFile ;//用于清除刚上传的文件
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + merDevInfoService + queryPageListMethod;
		
		var param = "";
		//搜索参数
		if ($("#queryMerDevNameLike").val()!=''){
			param += "queryMerDevNameLike="+$("#queryMerDevNameLike").val();
		}
		if ($("#queryMerDevCode").val()!=''){
			param += "&queryMerDevCode="+$("#queryMerDevCode").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",userId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					        		{name: 'MerDev_ID', label: '主键', width: 0},
					        	 	{name: 'MerDev_Code', label: '设备号', width: 150},
						            {name: 'MerDevName', label: '投放名称', width: 134},
						            {name: 'SN', label: '硬件序列号', width: 109},
						            {name: 'DevWorkStatusText', label: '设备状态', width: 109},
						            {name: 'MerDevStatusText', label: '审核状态', width: 109},
						            {name: 'Opr_Date', label: '操作日期', width: -1}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					$('#listDataGrid').data('zui.datagrid').sortBy('DevInf_ID', 'asc');
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	//初始化添加
	$("#addBtn").click(function(){
		//获取所属厂商列表
		var url = adminQueryUrl + merDevInfoService +initAddMethod ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				if (data.success=='1'){
					document.getElementById("addDevInf_Code").options.length=1;
					$.each(data.devInfoList, function(i, item){ 
						$("#addDevInf_Code").append("<option value='"+item.DevInf_ID+"'>"+item.DevInf_Code+"</option>");
					});
					$.fn.zTree.init($("#addtreeDemo"), setting, data.areaList);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});

		
	});
	//添加保存
	$("#addSaveBtn").click(function(){
			$("#addForm").validate({
				rules:{
					addMerDevName:{
						"required":true
					},
					addArea_Code:{
						"required":true
					},
					addDevInf_Code:{
						"remote":{
							url:adminQueryUrl +  merDevInfoService + "/validate.action",
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addDevInf_Code':function(){
									return $("#addDevInf_Code").val();
								}
							}
						}
					}
				},
				messages:{
					addMerDevName:{
						"required":"请输入投放名称！"
					},
					addArea_Code:{
						"required":"请选择所属地区！"
					},
					addDevInf_Code:{
						"required":"请选择设备编码！",
						"remote":"该设备编码不合法请选择其他编码！"
					}
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  merDevInfoService + addMethod);
					
					$.ajax({
						url:adminQueryUrl + merDevInfoService + addMethod ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('添加data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + merDevInfoService +initUpdateMethod;
			var param = 'DevInfoId='+selectedItems[0].MerDev_ID;
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('初始化修改data='+data);
					if (data.success=='1'){
						document.getElementById("updateDevInf_Code").options.length=1;
						$.each(data.devInfoList, function(i, item){ 
							if(item.DevInf_ID==data.merDevMap.DevInf_Code){
								console.log(item.DevInf_Code+"=="+data.merDevMap.DevInf_Code)
								$("#updateDevInf_Code").append("<option value='"+item.DevInf_ID+"' selected='selected'>"+item.DevInf_Code+"</option>");
							}else{
								$("#updateDevInf_Code").append("<option value='"+item.DevInf_ID+"'>"+item.DevInf_Code+"</option>");
							}
						});
						$.each(data.MerDevStatusList, function(i, item){
							if(item.key_value==data.merDevMap.MerDevStatus){
								console.log(item.key_value+"=="+data.merDevMap.MerDevStatus)
								$("#updateMerDevStatus").val(item.key_name);
							}
						});
						$.each(data.DevWorkStatusList, function(i, item){
							if(item.key_value==data.merDevMap.DevWorkStatus){
								console.log(item.key_value+"=="+data.merDevMap.DevWorkStatus)
								$("#updateDevWorkStatus").val(item.key_name);
							}
						});
						$.fn.zTree.init($("#updatetreeDemo"), settingUpdate, data.areaList);
						$("#updateMerDev_Code").val(data.merDevMap.MerDev_Code);
						$("#updateMerDevName").val(data.merDevMap.MerDevName);
						$("#updateLongitude").val(data.merDevMap.Longitude);
						$("#updateLatitude").val(data.merDevMap.Latitude);
						$("#updateDeliveryAddress").val(data.merDevMap.DeliveryAddress);
						$("#updateDevHwVer").val(data.merDevMap.DevHwVer);
						$("#updateDevAppVer").val(data.merDevMap.DevAppVer);
						$("#updateDevParamVer").val(data.merDevMap.DevParamVer);
						$("#updateDevOtherVer").val(data.merDevMap.DevOtherVer);
						$("#updateSN").val(data.merDevMap.SN);
						$.each(data.areaList, function(i, item){
							if(item.areaCode==data.merDevMap.Area_Code){
								console.log(item.areaCode+"=="+data.merDevMap.Area_Code)
								$("#updatecitySel").val(item.areaName);
								$("#updateArea_Code").val(data.merDevMap.Area_Code);
							}
						});
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//修改保存
	$("#updateSaveBtn").click(function(){
		var DevInfoId = $('#listDataGrid').data('zui.datagrid').getCheckItems()[0].MerDev_ID;
		console.log("修改保存的ID="+DevInfoId);
		$("#excludeId").val(DevInfoId);
		var validUrl = adminQueryUrl + merDevInfoService + "/validate.action";
		$("#updateForm").validate({
			rules:{
				updateDevInf_Code:{
					"required":true,
					"remote":{
						url:validUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'updateDevInf_Code':function(){
								return $("#updateDevInf_Code").val();
							},
							'excludeId':function(){
								return $("#excludeId").val();
							}
						}
					}
				},
				updateMerDevName:{
					"required":true,
				},
				updateArea_Code:{
					"required":true,
				}
				
			},
			messages:{
				updateDevInf_Code:{
					"required":"请选择设备编码！",
					"remote":"该设备编码不合法，请选择其他编码！"
				},
				updateMerDevName:{
					"required":"请输入投放名称！",
				},
				updateArea_Code:{
					"required":"请选择所属地区！",
				}
			},
			submitHandler:function(form){
				var saveUrl = adminQueryUrl + merDevInfoService + updateMethod;
				$.ajax({
					url:saveUrl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					header:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	queryListFun();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
			
		
		
		
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + merDevInfoService + detailMethod;
			var param = 'DevInfoId='+selectedItems[0].MerDev_ID;//请求到列表页面
			console.log('详情param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('详情data='+data);
					if (data.success=='1'){
						$.each(data.devInfoList, function(i, item){ 
							if(item.DevInf_ID==data.merDevMap.DevInf_Code){
								console.log(item.DevInf_Code+"=="+data.merDevMap.DevInf_Code)
								$("#detailDevInf_Code").val(item.DevInf_Code);
							}
						});
						$.each(data.MerDevStatusList, function(i, item){
							if(item.key_value==data.merDevMap.MerDevStatus){
								console.log(item.key_value+"=="+data.merDevMap.MerDevStatus)
								$("#detailMerDevStatus").val(item.key_name);
							}
						});
						$.each(data.DevWorkStatusList, function(i, item){
							if(item.key_value==data.merDevMap.DevWorkStatus){
								console.log(item.key_value+"=="+data.merDevMap.DevWorkStatus)
								$("#detailDevWorkStatus").val(item.key_name);
							}
						});
						$("#detailMerDev_Code").val(data.merDevMap.MerDev_Code);
						$("#detailMerDevName").val(data.merDevMap.MerDevName);
						$("#detailLongitude").val(data.merDevMap.Longitude);
						$("#detailLatitude").val(data.merDevMap.Latitude);
						$("#detailDeliveryAddress").val(data.merDevMap.DeliveryAddress);
						$("#detailDevHwVer").val(data.merDevMap.DevHwVer);
						$("#detailDevAppVer").val(data.merDevMap.DevAppVer);
						$("#detailDevParamVer").val(data.merDevMap.DevParamVer);
						$("#detailDevOtherVer").val(data.merDevMap.DevOtherVer);
						$("#detailSN").val(data.merDevMap.SN);
						$.each(data.areaList, function(i, item){
							if(item.areaCode==data.merDevMap.Area_Code){
								console.log(item.areaCode+"=="+data.merDevMap.Area_Code)
								$("#detailcitySel").val(item.areaName);
							}
						});
						$("#detailOrg_Code").val(data.merDevMap.Org_Code);
						$("#detailAgeInf_Code").val(data.merDevMap.AgeInf_Code);
						$("#detailMerInf_Code").val(data.merDevMap.MerInf_Code);
						$("#detailCrtUserId").val(data.merDevMap.CrtUserId);
						$("#detailCrtDate").val(data.merDevMap.Crt_Date);
						$("#detailUptUserId").val(data.merDevMap.UptUserId);
						$("#detailLastUptDate").val(data.merDevMap.Opr_Date);
						$("#detailChkUserId").val(data.merDevMap.ChkUserId);
						$("#detailChkDate").val(data.merDevMap.Chk_Date);
						$("#detailChkRemark").val(data.merDevMap.ChkRemark);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteDevModelBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + merDevInfoService + deleteMethod;
		var param = 'DevInfo_ID='+selectedItems[0].MerDev_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	
});